/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.repository.rule;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author leyou
 */
@Component
public class InMemDegradeRuleStore extends InMemoryRuleRepositoryAdapter<DegradeRuleEntity> {

    private static AtomicLong ids = new AtomicLong(0);
    private static final ReentrantLock lock = new ReentrantLock();
    private static volatile boolean initialized = false;
    private String app;

    public String getApp() {
        return app;
    }

    public void setApp(String app) {
        this.app = app;
    }
    @Override
    protected long nextId() {
        ensureIdCounterInitialized();
        return ids.incrementAndGet();
    }
    /**
     * 确保ID计数器已初始化
     */
    private void ensureIdCounterInitialized() {
        if (!initialized) {
            lock.lock();
            try {
                if (!initialized) {
                    initializeIdCounter();
                }
            } finally {
                lock.unlock();
            }
        }
    }

    /**
     * 初始化ID计数器
     */
    private void initializeIdCounter() {
        // 简单实现：使用当前时间戳作为起始ID，避免与现有ID冲突
        List<DegradeRuleEntity> beforeSave = findAllByApp(app);
        long existId = 0;
        for (DegradeRuleEntity rule : beforeSave) {
            Long id = rule.getId();
            if (id > existId) {
                existId = id;
            }
        }
        ids.set(existId);

        initialized = true;
    }

    /**
     * 重写save方法，添加初始化检查
     */
    @Override
    public DegradeRuleEntity save(DegradeRuleEntity entity) {
        lock.lock();
        try {
            // 对于新实体且ID计数器未初始化时，进行初始化
            if (entity != null && entity.getId() == null && !initialized) {
                initializeIdCounter();
            }
            return super.save(entity);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 提供公共方法供外部调用以初始化ID计数器
     */
    public void forceInitialize() {
        ensureIdCounterInitialized();
    }
}
